package zw.netty.server.web;


import io.netty.buffer.Unpooled;
import org.springframework.context.event.EventListener;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Controller;
import org.springframework.web.socket.messaging.SessionDisconnectEvent;
import zw.netty.server.Netty.NettyServer;

import java.util.ArrayList;
import java.util.List;

/**
 * 创建人:zhuwei
 * 邮箱:121203654@qq.com
 * 创建时间:2018-08-15 10:32
 */
@Controller
public class WsController {
    public static int count=0;
    public static List<String> users=new ArrayList<>();

    @MessageMapping("/welcome")
    public int say(){
        count++;
        System.out.println(count);
        NettyServer.channelMap.forEach((key, channel)->{
            System.out.println(key);
            channel.writeAndFlush(Unpooled.copiedBuffer((count+"").getBytes()));
        });
        return 1;
    }

    //obd数据主题
    @SendTo("/topic/odb")
    public String OdbDate(){
        return "odb";
    }
    @SendTo("/topic/mpu6050")
    public String Sensor(){

        return "mpu6050";
    }
    @SendTo("/topic/odb")
    public String Odb(){

        return "odb";
    }
    @SendTo("/topic/shouhuan")
    public String shouhuan(){

        return "shouhuan";
    }
    @SendTo("/topic/gps")
    public String gps(){

        return "gps";
    }
    @EventListener
    public void onDisconnectEvent(SessionDisconnectEvent event) {
        count--;
        if(count<0){
            count=0;
        }
        NettyServer.channelMap.forEach((key, channel)->{
            channel.writeAndFlush(count+"");
        });
        System.out.println("Client with username {} disconnected:"+ count);
    }
}
